package com.leinao.task;

import com.leinao.file.dao.FileMapper;
import com.leinao.file.model.BandWidth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Random;

@Component
public class TaskService {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	public static Random random = new Random();
	
	@Autowired
	private FileMapper fileMapper;

    @Async("taskExecutor")
    public void doTaskOne(long start, String userId) throws Exception {
        log.info(" 开始做任务一 to {}", start);
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("完成任务一，耗时：" + (end - start) + "毫秒");
    }

    /**
     * 
     * 异步将用户资源流量入库
     * @param userId
     * @param bandWidth
     */
    @Async("taskExecutor")
    public void saveUserDownBandWidth(String userId, BigDecimal bandWidth) {
		log.info("userId: " + userId);
		log.info("user use bandWidth: " + bandWidth);

		BandWidth bandWidthBean = new BandWidth();
		bandWidthBean.setUserId(userId);
		bandWidthBean.setBandWidth(bandWidth.divide((new BigDecimal(1024)), 4, BigDecimal.ROUND_HALF_UP));
		try {
			fileMapper.insertUserDownBandWidth(bandWidthBean);
			log.info("insert file_center Down bandWidth success");
		} catch (Exception e) {
			log.error("insert file_center Down bandWidth failed" ,e);
		}
    }
    
    /**
     * 
     * 异步入库
     * @param userId
     * @param bandWidth
     */
    @Async("taskExecutor")
    public void saveFileData(String userId, BigDecimal bandWidth) {
		log.info("userId: " + userId);
		log.info("user use bandWidth: " + bandWidth);
		BandWidth bandWidthBean = new BandWidth();
		bandWidthBean.setUserId(userId);
		bandWidthBean.setBandWidth(bandWidth.divide((new BigDecimal(1024)), 4, BigDecimal.ROUND_HALF_UP));
		try {
			fileMapper.insertUserJobBandwidth(bandWidthBean);
			log.info("insert file_center bandWidth success");
		} catch (Exception e) {
			log.error("insert file_center bandWidth failed", e);
		}
    }
}